#include "terminal.h"
#include <QByteArray>
#include <QString>
#include <QDebug>

Terminal::Terminal(SerialPort *sp, QWidget *parent) : QMainWindow(parent)
{
    this->sp=sp;

    QObject::connect(sp, SIGNAL(portOpened()), this, SLOT(portOn()));
    QObject::connect(sp, SIGNAL(portClosed()), this, SLOT(portOff()));
    QObject::connect(sp, SIGNAL(dataReady()), this, SLOT(dataListener()));

    portOpen=false;
}

void Terminal::send(QString text)
{
    QByteArray bytes=text.toAscii();
    sp->send(bytes.size(),bytes.data());
    if(portOpen)
    {
        emit(dataReceived("<font color=blue>"+text+"</font>"));
    }
    else
    {
         emit(dataReceived("<font color=red>"+text+"</font>"));
    }
}

void Terminal::portOn()
{
    portOpen=true;
}

void Terminal::portOff()
{
    portOpen=false;
}

void Terminal::dataListener()
{
    char buffer[256];
    int rec=sp->receive(255,buffer);
    buffer[rec]='\0';
    emit(dataReceived(QString(buffer)));
}
